package com.yuque.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yuque.pojo.article;
import com.yuque.service.ArticleService;
import com.yuque.util.AliOSSProperties;
import com.yuque.util.Result;
import com.yuque.util.fenye;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/article")
@RestControllerAdvice
public class ArticleController {
    @ExceptionHandler(Exception.class)
    public Result xx(Exception ex){
        ex.printStackTrace();// 输出异常
        Result pp = new Result();
        pp.setFlag(false);
        pp.setShuju("服务器异常，等会再试");
        return pp;
    }
    @Autowired//将OSS的配置注入进来，后面需要用到
    private AliOSSProperties aliOSSProperties;
    @Autowired
    private ArticleService articleService;
    @RequestMapping("/selectfenye")
    public Result xx1(@RequestBody Map  map){
      fenye fenyecha = articleService.fenyecha(map);
        return new Result(true,fenyecha);
    }
    @RequestMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {

        // 为了防止不同用户传递相同名字的图片
        // 源文件的名字
        String oldname = file.getOriginalFilename();
        // 36位的随机组合 有字母和数字
        // 新名字
        String newName=  UUID.randomUUID().toString().substring(27)+"-"+oldname;
        InputStream inputStream = file.getInputStream();

        OSS oclient = new OSSClientBuilder().build(aliOSSProperties.getEndpoint(),aliOSSProperties.getAccessKeyId(),
                aliOSSProperties.getAccessKeySecret());
        // 把用户电脑上的图片的字节流(一个字节) 流到 bucketname对应的数据库中对应的新文件中
        oclient.putObject(aliOSSProperties.getBucketName(),newName,inputStream);

        //文件访问路径
        String url = aliOSSProperties.getEndpoint().split("//")[0] + "//" + aliOSSProperties.getBucketName() + "." + aliOSSProperties.getEndpoint().split("//")[1] + "/" + newName;

        System.out.println(url);
        // 关闭ossClient
        oclient.shutdown();

        return new Result(true,url);

    }
    @RequestMapping("/insert01")
    public Result xx2(@RequestBody article article){
        int insert = articleService.insert(article);
        return new Result(true,insert);
    }
    @RequestMapping("/selectByid/{id}")
    public Result xx3(@PathVariable Integer id){
        Map cha = articleService.cha(id);
        return new Result(true,cha);
    }
    @RequestMapping("delete01/{id}")
    public Result xx4(@PathVariable  Integer id){
        int i = articleService.deleteByid(id);
        return new Result(true,i);
    }
}
